/**
 * 数组转树形
 * list ://需要转化的json数组
 * idStr //唯一标识，键(key)名
 * pidStr //父级标识，父级键(key)名
 * childrenStr // 子集键（key）名
 * */
const invertTree = (list: any, idStr: string, pidStr: string, childrenStr: string) => {
    let newList = [], hash = {}, id = idStr, pid = pidStr, children = childrenStr, len = list.length;
    for (let i = 0; i < len; i++) {
        // @ts-ignore
        hash[list[i][id]] = list[i]
    }
    for (let i = 0; i < len; i++) {
        // @ts-ignore
        let val = list[i], hashVP = hash[val[pid]]
        if (hashVP) {
            !hashVP[children] && (hashVP[children] = []);
            hashVP[children].push(val);
        } else {
            newList.push(val);
        }
    }
    return newList;
}

/**
 * 树形数组扁平化
 * */
const revertTree = (treeList: any, childrenStr: string) => {
    revert(treeList)
    let result: [] = []
    function revert(list: any) {
        list.forEach((item: any) => {
            let obj = {}
            for (let key in item) {
                if (key != childrenStr) {
                    // @ts-ignore
                    obj[key] = item[key]
                }
            }
            // @ts-ignore
            result.push(obj)
            if (item[childrenStr]) {
                revert(item[childrenStr])
            }
        })
    }
    return result
}

export {
    invertTree,
    revertTree
}
